import React, {useEffect, useState} from 'react'
import {Form, Button, Input, Modal, Row, Col, message, Descriptions, DatePicker, Image, Upload} from 'antd'
import {connect} from 'umi'
import {genderList, isAuditList, registeredStatusList} from '@/utils/constant'
import {getUploadUrl} from "@/utils/upload";
import {UploadOutlined} from '@ant-design/icons';
import moment from 'moment'

const FormItem = Form.Item;
const {TextArea} = Input;

const formLayout = {
  labelCol: {span: 7},
};


const CreateForm = (props) => {
  const {onSubmit, onCancel, loading, visible, operateType, record} = props;
  const [form] = Form.useForm();
  const [title, setTitle] = useState('');
  const [operateStatus, setOperateStatus] = useState(null);
  const [fileUploadUrls, setFileUploadUrls] = useState([]);
  const [fileName, setFileName] = useState(null);


  useEffect(() => {
    if (visible && record) {
      switch (operateType) {
        case 0:
          setTitle('驳回');
          setOperateStatus(3);
          break;
        case 1:
          setTitle('审核');
          setOperateStatus(2);
          break;
        case 2:
          setTitle('详情');
          break;
        case 3:
          setTitle('解除');
          setOperateStatus(5);
          break;
      }
    }
  }, [visible]);

  const fileList = {
    name: 'file',
    multiple: false,
    action: getUploadUrl(),
    data: {name: fileName},
    beforeUpload(file) {
      setFileName(file.name)
    },
    onChange(res) {
      const {status} = res.file;
      if (status === 'done') {
        if (res.file.response.error) {
          message.success(`${res.file.response.error}`);
        } else {
          setFileUploadUrls([...fileUploadUrls, res.file.response]);
          message.success(`${res.file.name} 文件上传成功`);
        }
      } else if (status === 'error') {
        message.error(`${res.file.name} 文件上传失败`);
      }
    },
    onRemove(info) {
      let urls = fileUploadUrls;
      let index = urls.indexOf(info.url);
      if (index > -1)
        urls.splice(index, 1);
      setFileUploadUrls(urls);
    }
  };

  const onFormCancel = () => {
    form.resetFields();
    onCancel();
  };

  const handleSubmit = async () => {
    const fieldsValue = await form.validateFields();
    let id = record.id;
    let dataObj = {id, ...fieldsValue, status: operateStatus};
    operateType === 3 && (dataObj.fileUrl = fileUploadUrls.toString());
    onSubmit(dataObj);
    form.resetFields();
  };

  const renderContent = () => {
    return (
      <>
        <Descriptions column={2}>
          <Descriptions.Item label="姓名">{record && record.name}</Descriptions.Item>
          <Descriptions.Item label="身份证">{record && record.idcard}</Descriptions.Item>
          <Descriptions.Item label="性别">{record && genderList.find(item => item.value===record.gender)?.label}</Descriptions.Item>
          <Descriptions.Item label="出生年月">{record && record.birthday}</Descriptions.Item>
          <Descriptions.Item label="证书编号">{record && record.credentialNo}</Descriptions.Item>
          <Descriptions.Item label="管理编号">{record && record.mangerNo}</Descriptions.Item>
          <Descriptions.Item label="授予时间">{record && moment(record.startTime).format('YYYY-MM-DD')}</Descriptions.Item>
          <Descriptions.Item label="到期时间">{record && moment(record.endTime).format('YYYY-MM-DD')}</Descriptions.Item>
          <Descriptions.Item label="证书级别">{record && record.credentialLevel}</Descriptions.Item>
          <Descriptions.Item label="职称系列">{record && record.jobSeries}</Descriptions.Item>
          <Descriptions.Item label="资格名称">{record && record.credentialName}</Descriptions.Item>
          <Descriptions.Item label="专业">{record && record.profession}</Descriptions.Item>
          <Descriptions.Item label="批准机关">{record && record.approvalAuthority}</Descriptions.Item>
          <Descriptions.Item label="注册单位">{record && record.registerOrg}</Descriptions.Item>
          <Descriptions.Item label="是否年审">{record && isAuditList.find(item => item.value===record.isAudit)?.label}</Descriptions.Item>
          <Descriptions.Item label="是否挂证">{record && registeredStatusList.find(item => item.value===record.hangStatus)?.label}</Descriptions.Item>
          <Descriptions.Item label="挂证审批状态">{record && registeredStatusList.find(item => item.value===record.audit)?.label}</Descriptions.Item>
        </Descriptions>
        <Descriptions>
          <Descriptions.Item label="证件照片">
            {
              (record && record.fileUrl) && record.fileUrl.split(',').map((item,index) => (
                <Image key={index} style={{margin:'10px'}} width={200} src={item}/>
              ))
            }
          </Descriptions.Item>
        </Descriptions>
        {
          (record && record.audit === 2) &&
          <Descriptions column={2}>
            <Descriptions.Item label="补贴金额">{record && record.allowance}</Descriptions.Item>
            <Descriptions.Item label="补贴发放时间">{record && moment(record.allowanceTime).format('YYYY-MM-DD')}</Descriptions.Item>
          </Descriptions>
        }
        {
          (record && record.audit === 3) &&
          <Descriptions>
            <Descriptions.Item label="驳回原因">{record && record.reason}</Descriptions.Item>
          </Descriptions>
        }
        {
          (record && record.audit === 5) &&
          <Descriptions column={2}>
            <Descriptions.Item label="解除原因">{record && record.reason}</Descriptions.Item>
            <Descriptions.Item label="解除附件">
              {
                (record && record.refuseUrl) && record.refuseUrl.split(',').map((item,index) => (
                  <a href={item}>{item.split('----')[1]}</a>
                ))
              }
            </Descriptions.Item>
          </Descriptions>
        }

        {
          /*operateType===1 &&
          <Row gutter={24}>
            <Col span={10}>
              <FormItem name="allowance" labelCol={2} label="补贴金额：" rules={[{required: true, message: '补贴金额不能为空'}]}>
                <Input/>
              </FormItem>
            </Col>
            <Col span={14}>
              <FormItem name="allowanceTime" labelCol={{span: 6}} label="补贴发放时间：" rules={[{required: true, message: '请选择补贴发放时间'}]}>
                <DatePicker className='widthStyle'/>
              </FormItem>
            </Col>
          </Row>*/
        }
        {
          operateType===0 &&
          <FormItem name="reason" labelCol={2} label="驳回原因" rules={[{required: true, message: '驳回原因不能为空'}]}>
            <TextArea rows={4}/>
          </FormItem>
        }
        {
          operateType===3 &&
          <Row gutter={24}>
            <Col span={24}>
              <FormItem name="reason" labelCol={2} label="解除原因" rules={[{required: true, message: '解除原因不能为空'}]}>
                <TextArea rows={3}/>
              </FormItem>
            </Col>
            <Col span={24}>
              <FormItem name="urlIds" labelCol={2} label="解除附件" rules={[{required: true, message: '解除附件不能为空！'}]}>
                <Upload {...fileList}>
                  <Button>
                    <UploadOutlined/> 点击上传附件
                  </Button>
                </Upload>
              </FormItem>
            </Col>
          </Row>
        }
      </>
    )
  };

  const renderFooter = () => {
    return (
      <>
        <Button onClick={() => onFormCancel()}>{operateType !== 2 ?'取消':'关闭'}</Button>
        {
          operateType !== 2 &&
          <Button type="primary" onClick={() => handleSubmit()} loading={loading}>{operateType === 0 ? '驳回' : '确定'}</Button>
        }
      </>
    )
  };

  return (
    <Modal
      width='75%'
      title={title}
      visible={visible}
      bodyStyle={{padding: '0 5%'}}
      footer={renderFooter()}
      onCancel={() => onFormCancel()}
    >
      <Form
        {...formLayout}
        form={form}
        style={{paddingTop: '24px'}}
      >
        {renderContent()}
      </Form>
    </Modal>
  )
}

export default connect(({user}) => ({
  currentUser: user.currentUser,
}))(CreateForm)
